﻿using Microsoft.AspNetCore.Mvc;
using wenzhen.Models;
using wenzhen.Data;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using System;

[ApiController]
[Route("api/[controller]")]
public class DiagnosisController : Controller
{
    private readonly ApplicationDbContext _context;

    public DiagnosisController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpPost("SaveAdvice")]
    //public IActionResult SaveAdvice([FromBody] TreatmentAdviceDto model)
    public async Task<IActionResult> SaveAdvice([FromBody] TreatmentAdviceDto model)
    {
        if (string.IsNullOrEmpty(model.StudentID) || string.IsNullOrEmpty(model.TreatmentAdvice))
        {
            return BadRequest(new { success = false, message = "参数错误" });
        }

        var diagnosis = _context.Diagnosis.FirstOrDefault(d => d.StudentID == model.StudentID);
        if (diagnosis == null)
        {
            return NotFound(new { success = false, message = "未找到对应诊断" });
        }

        diagnosis.TreatmentAdvice = model.TreatmentAdvice;
        _context.SaveChanges();

        return Ok(new { success = true });
    }
    // 获取诊断详情
    [HttpGet("Details")]
    public IActionResult Details([FromQuery] string studentID)
    {
        if (string.IsNullOrEmpty(studentID))
        {
            return BadRequest(new { message = "StudentID is required." });
        }

        var diagnosis = _context.Diagnosis
            .Where(d => d.StudentID == studentID)
            .Select(d => new DiagnosisRequestDto
            {
                StudentID = d.StudentID,
                TreatmentAdvice = d.TreatmentAdvice,  // 加载调理建议
                GeneralSymptoms = d.GeneralSymptoms,
                CurrentSymptoms = d.CurrentSymptoms,
                Appetite = d.Appetite,
                MorningFeeling = d.MorningFeeling,
                ColdSensitivity = d.ColdSensitivity,
                SleepIssues = d.SleepIssues,
                StoolDetails = d.StoolDetails,
                UrineDetails = d.UrineDetails,
                TongueImageFront = d.TongueImageFront,
                TongueImageBack = d.TongueImageBack,
                BloodPressure = d.BloodPressure,
                Emotions = d.Emotions,
                TemperatureSensitivity = d.TemperatureSensitivity,
                MenstrualStatus = d.MenstrualStatus,
                MedicalHistory = d.MedicalHistory,
                WaterPreference = d.WaterPreference,
                Name = _context.PatientInfos.Where(p => p.StudentID == studentID).Select(p => p.Name).FirstOrDefault(),
                Gender = _context.PatientInfos.Where(p => p.StudentID == studentID).Select(p => p.Gender).FirstOrDefault(),
                SickDate = _context.PatientInfos.Where(p => p.StudentID == studentID).Select(p => p.SickDate).FirstOrDefault(),
                BirthDate = _context.PatientInfos.Where(p => p.StudentID == studentID).Select(p => p.BirthDate).FirstOrDefault(),
                BirthPlace = _context.PatientInfos.Where(p => p.StudentID == studentID).Select(p => p.BirthPlace).FirstOrDefault(),
                CurrentLocation = _context.PatientInfos.Where(p => p.StudentID == studentID).Select(p => p.CurrentLocation).FirstOrDefault(),
                Height = _context.PatientInfos.Where(p => p.StudentID == studentID).Select(p => p.Height).FirstOrDefault(),
                Weight = _context.PatientInfos.Where(p => p.StudentID == studentID).Select(p => p.Weight).FirstOrDefault(),
                RequestTime = _context.PatientInfos.Where(p => p.StudentID == studentID).Select(p => p.RequestTime).FirstOrDefault(),

                // 新增脉诊字段
                LeftCunFloat = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.LeftCunFloat).FirstOrDefault(),
                LeftCunMiddle = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.LeftCunMiddle).FirstOrDefault(),
                LeftCunDeep = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.LeftCunDeep).FirstOrDefault(),
                LeftGuanFloat = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.LeftGuanFloat).FirstOrDefault(),
                LeftGuanMiddle = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.LeftGuanMiddle).FirstOrDefault(),
                LeftGuanDeep = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.LeftGuanDeep).FirstOrDefault(),
                LeftChiFloat = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.LeftChiFloat).FirstOrDefault(),
                LeftChiMiddle = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.LeftChiMiddle).FirstOrDefault(),
                LeftChiDeep = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.LeftChiDeep).FirstOrDefault(),
                RightCunFloat = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.RightCunFloat).FirstOrDefault(),
                RightCunMiddle = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.RightCunMiddle).FirstOrDefault(),
                RightCunDeep = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.RightCunDeep).FirstOrDefault(),
                RightGuanFloat = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.RightGuanFloat).FirstOrDefault(),
                RightGuanMiddle = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.RightGuanMiddle).FirstOrDefault(),
                RightGuanDeep = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.RightGuanDeep).FirstOrDefault(),
                RightChiFloat = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.RightChiFloat).FirstOrDefault(),
                RightChiMiddle = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.RightChiMiddle).FirstOrDefault(),
                RightChiDeep = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.RightChiDeep).FirstOrDefault(),
                PulseSummary = _context.PulseDiagnoses.Where(p => p.StudentID == studentID).Select(p => p.PulseSummary).FirstOrDefault()
            })
            .FirstOrDefault();

        if (diagnosis == null)
        {
            return NotFound(new { message = "Diagnosis not found." });
        }
        // 获取该姓名对应的所有历史编号（排除当前编号）
        var historyStudentIDs = (from d in _context.Diagnosis
                                 join p in _context.PatientInfos on d.StudentID equals p.StudentID
                                 where d.StudentID != studentID && p.Name == diagnosis.Name
                                 orderby p.RequestTime descending // 按 RequestTime 倒序排序
                                 select d.StudentID)
                                 .ToList();


        diagnosis.HistoryStudentIDs = string.Join(", ", historyStudentIDs);

        return View(diagnosis);
        //return Ok(diagnosis); // 返回诊断详情
    }


    // 上传舌像图片
    [HttpPost("upload-tongue-images")]
    public async Task<IActionResult> UploadTongueImages([FromForm] IFormFile TongueImageFront, [FromForm] IFormFile TongueImageBack)
    {
        if ((TongueImageFront == null || TongueImageFront.Length == 0) && (TongueImageBack == null || TongueImageBack.Length == 0))
        {
            return BadRequest(new { message = "请上传正面和反面照片。" });
        }

        // 文件大小和类型限制
        const long maxFileSize = 10 * 1024 * 1024; // 10MB
        var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif" };

        var uploadFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Uploads");
        if (!Directory.Exists(uploadFolder))
        {
            Directory.CreateDirectory(uploadFolder);
        }

        var response = new Dictionary<string, object>();

        // 文件上传处理函数
        async Task<string> UploadImage(IFormFile file)
        {
            if (file != null && file.Length > 0)
            {
                if (file.Length > maxFileSize)
                {
                    return $"文件 {file.FileName} 超过最大上传限制 ({maxFileSize / 1024 / 1024} MB)";
                }

                var extension = Path.GetExtension(file.FileName).ToLower();
                if (!allowedExtensions.Contains(extension))
                {
                    return $"文件 {file.FileName} 类型不允许，仅支持 jpg, jpeg, png, gif 格式";
                }

                var filePath = Path.Combine(uploadFolder, Guid.NewGuid().ToString() + extension);
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                return $"/Uploads/{Path.GetFileName(filePath)}";
            }
            return null;
        }

        // 上传正面和反面照片
        var frontImagePath = await UploadImage(TongueImageFront);
        if (frontImagePath != null)
        {
            response["TongueImageFront"] = frontImagePath;
        }

        var backImagePath = await UploadImage(TongueImageBack);
        if (backImagePath != null)
        {
            response["TongueImageBack"] = backImagePath;
        }

        if (!response.ContainsKey("TongueImageFront") && !response.ContainsKey("TongueImageBack"))
        {
            return BadRequest(new { message = "正面和反面照片均未上传或格式不正确。" });
        }

        return Ok(response);
    }

    [HttpPost("add-diagnosis")]
    public async Task<IActionResult> AddDiagnosis([FromBody] DiagnosisRequestDto dto )
    {

        if (dto == null)
        {
            return BadRequest(new { message = "Diagnosis data is required." });
        }

        using var transaction = _context.Database.BeginTransaction();
            try
            {
                // 处理 PatientInfos 表
                var patient = _context.PatientInfos.FirstOrDefault(p => p.StudentID == dto.StudentID);

                if (patient == null)
                {
                    patient = new PatientInfos
                    {
                        Name = dto.Name,
                        Gender = dto.Gender,
                        StudentID = dto.StudentID,
                        SickDate = dto.SickDate ?? "",
                        BirthDate = dto.BirthDate ?? "",
                        BirthPlace = dto.BirthPlace,
                        CurrentLocation = dto.CurrentLocation,
                        Height = dto.Height,
                        Weight = dto.Weight,
                        RequestTime = dto.RequestTime ?? DateTime.Now
                    };
                    _context.PatientInfos.Add(patient);
                }
                else
                {
                    patient.Name = dto.Name ?? patient.Name;
                    patient.Gender = dto.Gender ?? patient.Gender;
                    patient.SickDate = dto.SickDate ?? patient.SickDate;
                    patient.BirthDate = dto.BirthDate ?? patient.BirthDate;
                    patient.BirthPlace = dto.BirthPlace ?? patient.BirthPlace;
                    patient.CurrentLocation = dto.CurrentLocation ?? patient.CurrentLocation;
                    patient.Height = dto.Height ?? patient.Height;
                    patient.Weight = dto.Weight ?? patient.Weight;
                    patient.RequestTime = dto.RequestTime ?? patient.RequestTime;
                    _context.PatientInfos.Update(patient);
                }

                _context.SaveChanges();

                // 处理 Diagnosis 表
                var diagnosis = new Diagnosis
                {
                    StudentID = patient.StudentID,
                    GeneralSymptoms = dto.GeneralSymptoms,
                    CurrentSymptoms = dto.CurrentSymptoms,
                    Appetite = dto.Appetite,
                    MorningFeeling = dto.MorningFeeling,
                    ColdSensitivity = dto.ColdSensitivity,
                    SleepIssues = dto.SleepIssues,
                    StoolDetails = dto.StoolDetails,
                    UrineDetails = dto.UrineDetails,
                    TongueImageFront = dto.TongueImageFront, // 保存上传的正面图片路径
                    TongueImageBack = dto.TongueImageBack,   // 保存上传的反面图片路径
                    BloodPressure = dto.BloodPressure,
                    Emotions = dto.Emotions,
                    TemperatureSensitivity = dto.TemperatureSensitivity,
                    MenstrualStatus = dto.MenstrualStatus,
                    MedicalHistory = dto.MedicalHistory,
                    WaterPreference = dto.WaterPreference
                };

                _context.Diagnosis.Add(diagnosis);
                _context.SaveChanges();

            // 处理 PulseDiagnoses 表
            var PulseDiagnoses = new PulseDiagnosis
            {
                StudentID = patient.StudentID,
                LeftCunFloat = dto.LeftCunFloat,
                LeftCunMiddle = dto.LeftCunMiddle,
                LeftCunDeep = dto.LeftCunDeep,
                LeftGuanFloat = dto.LeftGuanFloat,
                LeftGuanMiddle = dto.LeftGuanMiddle,
                LeftGuanDeep = dto.LeftGuanDeep,
                LeftChiFloat = dto.LeftChiFloat,
                LeftChiMiddle = dto.LeftChiMiddle,
                LeftChiDeep = dto.LeftChiDeep,
                RightCunFloat = dto.RightCunFloat,
                RightCunMiddle = dto.RightCunMiddle,
                RightCunDeep = dto.RightCunDeep,
                RightGuanFloat = dto.RightGuanFloat,
                RightGuanMiddle = dto.RightGuanMiddle,
                RightGuanDeep = dto.RightGuanDeep,
                RightChiFloat = dto.RightChiFloat,
                RightChiMiddle = dto.RightChiMiddle,
                RightChiDeep = dto.RightChiDeep,
                PulseSummary = dto.PulseSummary
            };
            _context.PulseDiagnoses.Add(PulseDiagnoses);
                _context.SaveChanges();

                transaction.Commit();

                return Ok(new { message = "Data saved successfully.", StudentID = patient.StudentID });
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                return StatusCode(500, new { message = "An error occurred while saving to the database.", error = ex.Message });
            }
        

    }

   

}
